<template>
    <div class="content">
      <n-button type="info" @click="downloadCsv">导出CSV文件</n-button>
      <n-spin :show="loading" size="large">
        <n-data-table
          ref="tableRef" 
          :columns="columns"
          :data="roleList"
          :pagination="paginationReactive"
          :bordered="true"
          :scroll-x="true"
          :row-key="rowKey"
          striped
          style="margin-top: 70px; max-height: 700px;" 
          :get-csv-cell="getCsvCell"
          :get-csv-header="getCsvHeader"
        />
      </n-spin>
    </div>
  </template>
  
  <script setup>
  import { h,onMounted, reactive, ref } from 'vue';
  import { NButton, NDataTable, NSpin,NTag,NCard,NCheckbox } from 'naive-ui';
  import axiosInstance from '@/utils/axios';
  
  
  const tableRef = ref(null); // 用于获取表格的ref
  
  const columns = createColumns({});
  const rowKey = (row) => row.role_id;
  const menuAccessMap = reactive({})

  // 获取角色权限数据
const fetchRoleMenuAccess = async (row) => {
  const roleId = row.role_id;
  if (menuAccessMap[roleId]) return; // 已加载过则不重复加载

  try {
    const response = await axiosInstance.get("/api/get_role_menu_access", {
      params: { role_id: roleId },
    });
    if (response.data.success) {
      menuAccessMap[roleId] = response.data.data;
      
    } else {
      console.error("获取角色权限失败");
    }
  } catch (error) {
    console.error("请求角色权限接口失败", error);
  }
};

// 更新角色权限
const updateRoleAccess = async (roleId, accessId, checked) => {
  try {
    const response = await axiosInstance.get('/api/update_role_access', {
      params: { role_id: roleId, access_id: accessId },
    });

    console.log(response)
    if (response.data.success) {
      console.log(`更新角色权限成功: Role ID = ${roleId}, Access ID = ${accessId}`);
      // 更新本地数据状态
      menuAccessMap[roleId] = menuAccessMap[roleId].map((access) => {
        if (access.access_id === accessId) {
          access.use = checked; // 更新选中状态
        }
        return access;
      });
    } else {
      console.error(`更新角色权限失败: ${response.data.message}`);
    }
  } catch (error) {
    console.error('请求更新角色权限接口失败', error);
  }
};


  // 表格列定义
  function createColumns() {
    return [
        {
        type: "expand",
        renderExpand: (row) => {
          fetchRoleMenuAccess(row)
          return h(
          NCard,
          { style: { width: "100%", height: "200px" }, title: "角色权限菜单" },
          [
          h(
            "div",
            {
              style: {
                display: "grid",
                gridTemplateColumns: "repeat(4, 1fr)", // 每行四列
                gap: "8px", // 间距
              },
            },
            (menuAccessMap[row.role_id] || []).map((access) =>
              h(NCheckbox, { checked: access.use,
                "onUpdate:checked": (checked) => updateRoleAccess(row.role_id, access.access_id, checked) }, 
                { default: () => access.access_name })
            )
          ),
          ]
        );
        }
      },
      {
        title: '创建时间',
        key: 'create_time',
        width: 200,
        ellipsis: { tooltip: true },
      },
      {
        title: '角色编号',
        key: 'role_id',
        width: 100,
        ellipsis: { tooltip: true },
      },
      {
        title: '角色名称',
        key: 'role_name',
        width: 100,
        ellipsis: { tooltip: true },
        render(row) {
        let roleColor = 'default';
        if (row.role_name === '管理员') {
          roleColor = 'error';
        } else if (row.role_name === '用户') {
          roleColor = 'success';
        } else if (row.role_name === '客服') {
          roleColor = 'warning';
        }
        return h(NTag, { type: roleColor }, row.role_name);
      }
      },
      {
        title: '角色介绍',
        key: 'role_desc',
        width: 300,
        ellipsis: { tooltip: true },
      },
    ];
  }
  
  // 表格数据（使用reactive）和分页配置
  const roleList = reactive([]);
  const maxpage = ref(0);
  const loading = ref(false);
  
  const paginationReactive = reactive({
    page: 1,
    pageSize: 10,
    showSizePicker: true,
    pageSizes: [3, 5, 10],
    onChange(page) {
      loading.value = true;
      if (page > paginationReactive.page && page > maxpage.value) {
        paginationReactive.page = page;
        fetchRoleList(page, paginationReactive.pageSize);
      } else {
        paginationReactive.page = page;
        loading.value = false;
      }
    },
    onUpdatePageSize(pageSize) {
      paginationReactive.pageSize = pageSize;
      paginationReactive.page = 1;
    },
  });
  
  // 获取区域列表数据
  const fetchRoleList = async (page = 1, pageSize = 500) => {
    try {
      loading.value = true;
      const response = await axiosInstance.post('/api/get_role_list',
      { page, page_size: pageSize },
      );
  
      if (response.data.success) {
        roleList.push(...response.data.data);
        maxpage.value = Math.ceil(response.data.total / paginationReactive.pageSize);
      } else {
        console.error('没有区域数据');
      }
    } catch (error) {
      console.error('请求失败', error);
    } finally {
      loading.value = false;
    }
  };
  
  
  onMounted(() => {
    fetchRoleList();
  });
  
  // 导出CSV的函数
  const downloadCsv = () => {
    // 获取列定义
    const columnsForCsv = columns.map(col => ({
      title: col.title,
      key: col.key,
    }));
  
    // 格式化表格数据
    const dataForCsv = roleList.map(user => {
      const row = {};
      columnsForCsv.forEach(col => {
        if (col.key === 'user_status') {
          // 转换 user_status 为 可用 或 禁用
          row[col.key] = user[col.key] === 1 ? '可用' : '禁用';
        } else {
          row[col.key] = user[col.key];
        }
      });
      console.log(row)
      return row;
    });
  
    tableRef.value?.downloadCsv({
      fileName: "user-list",
      data: dataForCsv,
      columns: columnsForCsv
    });
  };
  </script>
  
  <style scoped>
  .content {
    margin-left: 60px;
    margin-top: 20px;
    height: 1000px;
    width: 1130px;
  }
  </style>
  